<template>
  <section>
    <div v-if="loadAble">
      <el-button size="mini" type="text" @click="loadDialogBtn" style="margin-bottom: 10px;float:right;">导入产品</el-button>
    </div>
    <el-form label-width="40px" inline size="mini">
      <el-form-item label="来源" class="item">
        <sel-company :companyId="selCompanyId" v-on:confirm="selCompanyEvent"></sel-company>
        <sel-department v-if="selCompanyId" :companyId="selCompanyId" :departmentId="outboundForm.departmentId" v-on:confirm="selDepartmentEvent"></sel-department>
      </el-form-item>
      <el-form-item label="标题" class="item">
        <el-input size="mini" v-model="outboundForm.title" style="width: 100%"></el-input>
      </el-form-item>
      <el-form-item label="类型" class="item">
        <el-select size="mini" v-model="outboundForm.stockOutTypeCode">
          <el-option v-for="code in stockOutTypes" :key="code.id" :value="code.code" :label="code.name"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-table :data="outboundItems">
      <el-table-column type="index" label="序号"/>
      <el-table-column label="产品" prop="title">
        <template slot-scope="scope">
          <el-input v-if="scope.row.edit" size="mini" v-model="scope.row.title"></el-input>
          <span v-else>{{scope.row.title}}</span>
        </template>
      </el-table-column>
      <el-table-column label="规格" prop="data.props">
        <template slot-scope="scope">
          <el-input v-if="scope.row.edit" size="mini" v-model="scope.row.data.props"></el-input>
          <span v-else>{{scope.row.data.props}}</span>
        </template>
      </el-table-column>
      <el-table-column label="sn" prop="sn">
        <template slot-scope="scope">
          <el-input v-if="scope.row.edit" size="mini" @blur="getStockBySn($event,scope.row)" v-model="scope.row.sn"></el-input>
          <span v-else>{{scope.row.sn}}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" prop="unit">
        <template slot-scope="scope">
          <el-input v-if="scope.row.edit" size="mini" v-model="scope.row.unit"></el-input>
          <span v-else>{{scope.row.unit}}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" prop="num">
        <template slot-scope="scope">
          <el-input v-if="scope.row.edit" size="mini" v-model="scope.row.num"></el-input>
          <span v-else>{{scope.row.num}}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存" prop="virtualStock">
        <!--<template slot-scope="scope">-->
        <!--</template>-->
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <i :class="scope.row.edit?'el-icon-check':'el-icon-edit'" @click="scope.row.edit =!scope.row.edit" style="color:blue"/>
          <i class="el-icon-close" @click="delBtn(scope.$index)" style="color:red"/>
        </template>
      </el-table-column>
    </el-table>
    <div class="btnBox">
      <el-button size="mini" class="el-icon-plus" @click="addBtn"></el-button>
      <el-button size="mini" type="primary" @click="saveBtn">保存</el-button>
    </div>
    <el-dialog title="导入" :visible.sync="loadDialog" append-to-body width="80%">
      <load-by-stock :companyId="selCompanyId" v-on:confirm="selLoadEvent"></load-by-stock>
    </el-dialog>
  </section>
</template>

<script>
  import selDepartment from '@/common/selDepartment'
  import selCompany from '@/common/selCompany'
  import loadByStock from './loadByStock'
  import {mapGetters, mapActions, mapMutations} from 'vuex'
  import Vue from 'vue'//后续添加属性，需要vue联动
  import errHandler from '@/assets/errHandler'
  export default {
    name: "new-outbound",
    components:{loadByStock,selCompany,selDepartment},
    props:['itemlist','task','companyId'],
    data(){
      return{
        stockOutTypes:[],
        outboundForm:{
          title:'',stockOutTypeCode:null,departmentId:null,warehouseId:null
        },
        outboundItems:[],
        loadDialog:false,
        loadAble:false,
        selCompanyId:null
      }
    },
    watch:{
      itemlist(nv,ov){
        console.log('少一个就不变了？？？',nv)
        if(nv) this.init(nv)
      },
      selCompanyId(nv,ov){
        console.log('切换公司-------',nv,ov)
        if(ov && this.outboundItems.length>0){
          this.$confirm('切换公司后，出库单内容将清空，请确定')
            .then(()=> {
              this.outboundItems=[]
              this.loadAble=true
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              })
              this.selCompanyId=ov
            })
        }
      }
    },
    computed: {
      ...mapGetters(['department']),
    },
    created(){
      console.log('当前项目----',this.itemlist)
      this.init(this.itemlist)
    },
    methods:{
      ...mapActions({
        fetch: 'fetch'
      }),
      getStockBySn(e,row){
        console.log('看一下-----------',e,row)
        Vue.set(row,'stock',100)
      },
      judgeLoadAble(){
        if(this.itemlist || this.task){//来源于任务和items
          return false
        }else {//直接手动创建
          return true
        }
      },
      init(nv){
        this.getStockOutTypes()
        let loadAble=this.judgeLoadAble()//判断是否可以导入产品
        if(loadAble){//是手动创建
          return
        }
        if(this.itemlist){//如果是item创建
          this.makeItemsByItemList(this.itemlist)
          return
        }
        if(this.task){//如果是出库任务创建
          this.makeItemsByTask()
          this.outboundForm=this.task
          let tmp=JSON.parse(this.task.outboundOrderItems)
          this.outboundItems=[]
          tmp.forEach(t=>{
            this.outboundItems.push(t)
          })
        }
        this.selCompanyId=this.companyId?this.companyId:null
        this.outboundItems=[]
        this.outboundForm.warehouseId=this.department.id

      },
      makeItemsByItemList(array){
        console.log('看下数据结构-------',array)
        for(let i=0;i<array.length;i++){
          let a=array[i]
        }
        array.forEach(a=>{
          a.specs.forEach(s=>{
            let index=this.outboundItems.findIndex(i=>i.sn === s.sn)
            if(index<0){
              let tmp={
                title:s.title.split('&&')[0],
                sn:s.sn,
                data:{props:s.title.split('&&')[1]},
                edit:false,
                unit:s.data.unit,
                virtualStock:s.virtualStock,
                realityStock:s.realityStock,
                num:1
              }
              this.outboundItems.push(tmp)
            }
          })
        })
        console.log('所有产品都导入好了------',this.outboundItems)
      },
      makeItemsByTask(){

      },
      getStockOutTypes(){
        this.fetch({name:"getStockOutTypes"})
          .then(res=>{
            // console.log(res)
            this.stockOutTypes=res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      delBtn(index){
        this.$confirm('确认删除？')
          .then(()=> {
            this.outboundItems.splice(index,1)
          })
          .catch(() => {
            this.$message({type: 'info',message: '已取消删除'})
            this.loading = false
          })
      },
      addBtn(){
        this.outboundItems.push({
          title:'',data:{props:''},sn:'',unit:'',num:'',edit:true
        })
      },
      saveBtn(){
        console.log('新建出库单----------',this.outboundForm,this.outboundItems)
        //判断出库单项数量
        if(this.outboundItems.length <=0){
          this.$message({type:'error',message:'请至少添加一个出库单项！'})
          return
        }
        //判断出库库存数量
        let ableList=[]
        for(let i=0;i<this.outboundItems.length;i++){
          let a=this.outboundItems[i]
          console.log('第一层？？？',a.num,a.virtualStock)
          if(a.num === undefined || a.num <=0 || a.num*1 > a.virtualStock){
            console.log('没到这里？？？')
            this.$message({type:'error',message:'请确认出库数量'})
            return
          }else {
            ableList.push(a)
          }
        }

        //判断sn是否存在
        this.judgeSn(ableList)
      },
      judgeSn(array){
        console.log('啥时候做到这里')
        //通过sn查询产品
        this.fetch({name:"getProductsBySn",data:{sn:array[0].sn}})
          .then(res=>{
            console.log('查询sn产品-----',res)
            if(res.length>0){
              array.splice(0,1)
            }else {
              this.$message({type:'error',message:'【'+array[0].title+'-sn'+array[0].sn+'】有误，请确认'})
              return
            }
            if(array.length<=0){
              //全部通过
              let outboundOrderItems=JSON.stringify(this.outboundItems)
              this.outboundForm.outboundOrderItems=outboundOrderItems
              //创建出库单
              this.createOutboundOrder(this.outboundForm)
            }else {
              this.judgeSn(array)
            }
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      createOutboundOrder(data){
        this.$confirm('保存后不许修改，确认保存？')
          .then(()=> {
            this.fetch({name:"createOutboundOrder",data:{...data,warehouseId:this.department.id}})
              .then(res=>{
                console.log('创建出库单成功-----',res)
                this.$message({type: 'success',message: '创建成功'})
                this.$emit('success')
              })
              .catch(err=>{
                console.log(err)
                errHandler.handle(this,err)
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      },
      selLoadEvent(e,d){
        console.log('导产品到出库单----',e,d)
        e.forEach(item=>{
          let index=this.outboundItems.findIndex(it=>it.sn === item.sn)
          if(index <0){
            let tmp={
              title:item.product.name,
              sn:item.sn,
              data:{props:item.props,companyId:item.product.companyId},
              unit:item.unit,num:'',
              edit:true
            }
            this.outboundItems.push(tmp)
          }
        })
        console.log('导入后的数据是？？？？',this.outboundItems)
        this.loadDialog=false
      },
      selCompanyEvent(e){
        console.log('切换公司-----',e)
        this.selCompanyId=e
      },
      selDepartmentEvent(e){
        this.outboundForm.departmentId=e
      },
      loadDialogBtn(){
        //先判断有没有公司
        this.loadDialog=true
      }
    }
  }
</script>

<style scoped>
  .item{
    border: 0px solid red;
    width: 45%;
  }
  .btnBox{
    margin-top: 10px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
</style>
